<template>
	<div class="chatAi">
		<van-sticky>
			<van-nav-bar title="人工智能&nbsp;小T" />
		</van-sticky>
		
		<div style="padding-bottom: 100px;">
			<div v-for="item in historyList">
				<div class="question">
					<div class="question_message">{{item.question}}</div>
					<div><img :src="userInfo.avatar" width="40px" height="40px" style="border-radius: 50%; margin-top: 10px;"></div>
				</div>
				<div class="answer" v-if="item.answer != null">
					<div><img src="../../assets/image/icon/chatGPT.png" width="40px" height="40px" style="margin-top:10px;"></div>
					<div v-html="markdown.render(item.answer)" class="answer_message"></div>
				</div>
			</div>
		</div>
		<footer>
			<div>
				<input type="text" placeholder="请输入对话内容" v-model="query" style="width: 100%; height: 44px; border:none; font-size: 15px;">
			</div>
			<div>
				<van-button type="success" @click="search()">发送</van-button>
			</div>
		</footer>
	</div>
</template>

<script>
	import { fetchEventSource } from '@microsoft/fetch-event-source';
	import MarkdownIt from 'markdown-it'
	import { showNotify } from 'vant'
	export default{
		data(){
			return{
				show: false,
				historyList:[],
				markdown: new MarkdownIt(),
				query: '',
				answer: '',
				userInfo: null
			}
		},
		mounted(){
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
			console.log(this.$route.params.sessionId);
			if(this.$route.query.q != null){
				this.query = this.$route.query.q;
				// this.search();
			}
			this.getHistory();
		},
		methods:{
			search(){
				if(this.query.trim().length == 0){
					showNotify({ type: 'warning', message: '消息内容不能为空' }); return;
				}
				this.historyList.push({question: this.query, answer: ''});
				this.query = "";
				let length = this.historyList.length;
				
				const eventSource = new EventSource(this.$api.CHAT + '?q=' + this.historyList[length - 1].question);
				eventSource.onmessage = (event) => {
					console.log(event);
					if(event.data == "") eventSource.close()
					this.historyList[length - 1].answer += event.data;
				}

				// let content = "";
				// fetchEventSource(this.$api.CHAT, {
				//     method: 'POST',
				//     headers: {
				//         'Content-Type': 'application/json',
				// 		"travel": localStorage.getItem("travel")
				//     },
				//     body: JSON.stringify({question: this.historyList[length - 1].question}),
				//     onmessage(event) {
				//         console.log(event);
				// 		content += event.data;
				//     },
				//     onclose() {
				// 		// console.log("end");
				// 		this.historyList[length - 1].answer = cotent;
				// 	}
				// })
			},
			getHistory(){
				let sessionId = this.$route.params.sessionId;
				this.$http.get(this.$api.SESSION_HISTORY, {
					params:{id: sessionId}
				}).then(result => {
					if(result.code == 200) this.historyList = result.body;
				})
			}
		}
	}
</script>

<style scoped>
	@import "../../assets/css/chat.css";
</style>